package cn.justweb;

import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*删除文件夹中没有使用的文件*/
public class AutoDelete {

    @Test
    public void clear() throws Exception{
        String basePath="C:\\Users\\yushanbo\\Desktop\\讲义\\笔记\\springboot\\笔记\\";

        //文件路径
        String filePath = basePath + "springboot.md";
        String content = streamToString(filePath);

        //正则表达式
        String pattern = "assets[/\\\\](.*)\\)";
        List<String> images = imageList(content, pattern);


        //图片路径
        String imagePath = basePath + "assets";
        File imageDir = new File(imagePath);
        File[] files = imageDir.listFiles();

        for (File file : files) {
            if(!images.contains(file.getName())){
                file.delete();
                System.out.println("删除文件"+file.getName()+"成功");
            }
        }

    }

    private List<String> imageList(String content, String pattern) {

        List<String> list = new ArrayList<>();

        // 创建 Pattern 对象
        Pattern p = Pattern.compile(pattern);

        // 现在创建 matcher 对象
        Matcher m = p.matcher(content);

        //将所有匹配到的数据保存到集合中
        while(m.find()){
          list.add(m.group(1));
            System.out.println(m.group(1));
        }


        return list;
    }

    public String streamToString(String filePath) throws Exception{
        InputStream inputStream = new FileInputStream(new File(filePath));
        String content = IOUtils.toString(inputStream, "UTF-8");
        return content;
    }
}
